from flask import Blueprint, current_app, abort, jsonify, render_template, request, g
from jinja2 import constants

from decorators import login_required
from exts import db
from image_storage import image_storage
from models import News
from response_code import RET
import constants

bp = Blueprint("publish",__name__,url_prefix="/publish")


@bp.route('/news_publish',methods=['GET','POST'])
@login_required
def get_news_publish():
    """
        1. 判断请求方式,如果是GET
        2. 携带分类数据渲染页面
        3. 如果是POST,获取参数
        4. 校验参数,为空校验
        5. 上传图片,判断是否上传成功
        6. 创建新闻对象,设置属性
        7. 保存到数据
        8. 返回响应
        :return:
        """


    if request.method == "GET":
        return render_template("news_publish.html")
#这边直接post请求
    title = request.form.get("title")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    polarity = request.form.get("polarity")
    # 4. 校验参数,为空校验
    if not all([title, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 5. 上传图片,判断是否上传成功
    try:
        # 读取图片为二进制数据,上传
        image_name = image_storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云异常")

    if not image_name:
        return jsonify(errno=RET.NODATA, errmsg="图片上传失败")

    # 6. 创建新闻对象,设置属性
    news = News()
    news.title = title
    news.source = g.user.username
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.polarity = polarity
    news.author_id = g.user.id


    # 7. 保存到数据
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻发布失败")

    # 8. 返回响应
    return jsonify(errno=RET.OK, errmsg="发布成功")
